import { GetRedisClient } from '@app/db/redis'
import { checkStatusImg, requestAvatar } from '@app/kandinsky'
import {} from 'redis'

interface AvatarInProgress {
  status: 'IN_PROGRESS'
}

interface AvatarDone {
  status: 'DONE'
  avatar: string
}

export type AvatarResult = AvatarInProgress | AvatarDone

export class AvatarService {
  private client: GetRedisClient

  constructor(client: GetRedisClient) {
    this.client = client
  }

  async setValue(key: string, value: string) {
    const client = await this.client()
    client.set(key, value)
  }

  async getValue(key: string): Promise<string | null> {
    const client = await this.client()
    return client.get(key)
  }

  // Метод для закрытия соединения с Redis
  async closeConnection(): Promise<void> {
    const client = await this.client()
    client.quit()
  }

  async create(email: string): Promise<AvatarResult> {
    let uuid = await this.getValue(email + ':uuid')
    if (!uuid) {
      const response = await requestAvatar(email)
      uuid = response.data.uuid
      await this.setValue(email + ':uuid', uuid)
      await this.setValue(uuid + ':status', response.data.status)

      return {
        status: 'IN_PROGRESS',
      }
    }
    const response = await checkStatusImg(uuid)
    if (response.data.status === 'DONE') {
      const avatar = response.data.images[0]
      await this.setValue(email + ':avatar', avatar)
      return {
        status: 'DONE',
        avatar,
      }
    }

    return {
      status: 'IN_PROGRESS',
    }
  }
}
